#!/usr/local/bin/ruby -w
require 'rubygems'
require 'twitter'
require 'highline/import'

# t_refriend.rb: Find out who we're following that doesn't follow us. Ask to
# re-follow those that don't.

# Just fulfilling a minor need on my part. My first Ruby chunk of code.
# Possibly someone else finds this useful. Just don't be annoying.
# It's a good thing the API limits us a little. There's hardly any error
# checking going on here.

class Twitter::Base
  # Get the screen name of an email
  def user_email(email)
    valid     = '[[:alnum:].+-]+'
    users(request("users/show.xml?email=#{email}", :auth => true)).first
  end

  # Simple bitswitch test wrapped around unimplemented API function
  def exists(user_a, user_b)
    are_friends = request(
      "friendships/exists?user_a=#{user_a}&user_b=#{user_b}",
      :auth => true
    )

    if are_friends.html == 'true'
      return 1
    else
      return nil
    end
  end

  # simple enuff
  def refollow(user)
    self.destroy_friendship(user)
    self.create_friendship(user)
  end
    
end

email   = ask('E-Mail address to log in to Twitter: ')
pw      = ask('Password: ') { |q| q.echo = false }

twitter = Twitter::Base.new(email, pw)

# Who am I & who do I follow? This only grabs latest 100 updaters due to API
# limits and to keep you honest and not so annoying.
t_me        = twitter.user_email(email).screen_name
t_fnames    = twitter.friends.map{ |f| f.screen_name }

# See if the tweeps we follow follow us too. Ask if we want to re-follow if
# they don't.
t_fnames.each do |f|
  if !twitter.exists(f, t_me)

    if agree("Re-follow #{f}? (y/n): ")
      twitter.refollow(f)
      puts "#{f} re-followed"
    else
      next
    end
  end
end
